<?php
// 安全过滤函数
function safe_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// 检查登录状态
function check_login() {
    // 如果是登录页面，不需要检查登录状态
    if (basename($_SERVER['PHP_SELF']) === 'login.php') {
        return;
    }
    
    if (!isset($_SESSION['admin_id'])) {
        header("Location: login.php");
        exit();
    }
}

// 获取当前页面名称
function get_current_page() {
    return str_replace('.php', '', basename($_SERVER['PHP_SELF']));
}

// 获取预约状态文本
function get_booking_status($status) {
    $status_map = [
        0 => '待确认',
        1 => '已确认',
        2 => '已取消',
        3 => '已完成'
    ];
    return isset($status_map[$status]) ? $status_map[$status] : '未知状态';
}

// 获取反馈状态文本
function get_feedback_status($status) {
    $status_map = [
        0 => '待处理',
        1 => '已处理',
        2 => '已关闭'
    ];
    return isset($status_map[$status]) ? $status_map[$status] : '未知状态';
}

/**
 * 生成分页HTML
 * @param int $page 当前页码
 * @param int $total_pages 总页数
 * @param array $params 其他URL参数
 * @return string 分页HTML
 */
function generate_pagination($page, $total_pages, $params = []) {
    if ($total_pages <= 1) return '';
    
    // 构建基础URL参数
    $url_params = [];
    foreach ($params as $key => $value) {
        if ($value !== '' && $value !== null && $value !== -1) {
            $url_params[] = $key . '=' . urlencode($value);
        }
    }
    $param_str = !empty($url_params) ? '&' . implode('&', $url_params) : '';
    
    $html = '<div class="pagination">';
    
    // 首页和上一页
    if ($page > 1) {
        $html .= '<a href="?page=1' . $param_str . '">&laquo; 首页</a>';
        $html .= '<a href="?page=' . ($page-1) . $param_str . '">上一页</a>';
    }
    
    // 显示当前页码附近的页码
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);
    
    for ($i = $start_page; $i <= $end_page; $i++) {
        $html .= '<a href="?page=' . $i . $param_str . '"' . 
                ($page == $i ? ' class="active"' : '') . '>' . $i . '</a>';
    }
    
    // 下一页和末页
    if ($page < $total_pages) {
        $html .= '<a href="?page=' . ($page+1) . $param_str . '">下一页</a>';
        $html .= '<a href="?page=' . $total_pages . $param_str . '">末页 &raquo;</a>';
    }
    
    $html .= '</div>';
    return $html;
}

// 检查权限
function check_permission($required_role) {
    if (!isset($_SESSION['role']) || $_SESSION['role'] < $required_role) {
        header("Location: error.php?msg=无权限访问");
        exit();
    }
}

// 格式化日期时间
function format_datetime($datetime, $format = 'Y-m-d H:i:s') {
    return date($format, strtotime($datetime));
}

// 生成随机字符串
function generate_random_string($length = 10) {
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}

// 处理文件上传
function handle_file_upload($file, $allowed_types, $upload_dir, $filename_prefix = '') {
    if ($file['error'] != 0) {
        return ['success' => false, 'message' => '文件上传失败'];
    }
    
    // 获取文件扩展名
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed_types)) {
        return ['success' => false, 'message' => '不允许的文件类型'];
    }
    
    // 确保目录存在并有写入权限
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
        chmod($upload_dir, 0777); // 确保目录有足够的权限
    }
    
    // 生成完整的文件名（包括扩展名）
    $filename = $filename_prefix ? $filename_prefix . $ext : uniqid() . '.' . $ext;
    $filepath = $upload_dir . $filename;
    
    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        chmod($filepath, 0644); // 设置适当的文件权限
        return [
            'success' => true,
            'filename' => $filename,
            'filepath' => $filepath
        ];
    }
    
    return ['success' => false, 'message' => '文件保存失败'];
}

// 删除文件
function delete_file($filepath) {
    if (file_exists($filepath)) {
        return unlink($filepath);
    }
    return false;
}

// 获取文件大小的可读格式
function format_file_size($size) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($size >= 1024 && $i < count($units) - 1) {
        $size /= 1024;
        $i++;
    }
    return round($size, 2) . ' ' . $units[$i];
}

// 记录系统日志
function log_activity($admin_id, $action, $details = '') {
    global $db;
    $stmt = $db->prepare("INSERT INTO admin_logs (admin_id, action, details, created_at) VALUES (?, ?, ?, NOW())");
    return $stmt->execute([$admin_id, $action, $details]);
}

// 获取客户端IP
function get_client_ip() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    }
    return $ip;
}

// 检查是否是Ajax请求
function is_ajax_request() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

// JSON响应
function json_response($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
    exit();
}

// 获取设置值
function get_setting($key, $default = null) {
    global $db;
    $stmt = $db->prepare("SELECT value FROM settings WHERE `key` = ?");
    $stmt->execute([$key]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? $result['value'] : $default;
}

// 更新设置值
function update_setting($key, $value) {
    global $db;
    $stmt = $db->prepare("INSERT INTO settings (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
    return $stmt->execute([$key, $value, $value]);
}

function redirect($url, $message = '', $type = 'success') {
    if ($message) {
        $_SESSION['message'] = $message;
        $_SESSION['message_type'] = $type;
    }
    header("Location: $url");
    exit;
}
